import os
from PIL import Image
import logging

# --- 配置 ---
# 设置目标文件夹路径
TARGET_FOLDER = "/root/data/Outdoor/SOTS/outdoor/gt/"
# 是否在转换成功后删除原始的PNG文件
DELETE_ORIGINAL_PNG = False

# --- 日志设置 ---
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    handlers=[logging.StreamHandler()])

def convert_png_to_jpg(folder_path):
    """
    将指定文件夹中的所有PNG图片转换为JPG格式。

    Args:
        folder_path (str): 包含PNG图片的文件夹路径。
    """
    if not os.path.isdir(folder_path):
        logging.error(f"错误：文件夹 '{folder_path}' 不存在。")
        return

    logging.info(f"开始扫描文件夹：'{folder_path}'")
    converted_count = 0
    skipped_count = 0

    # 遍历文件夹中的所有文件
    for filename in os.listdir(folder_path):
        if filename.lower().endswith('.png'):
            png_path = os.path.join(folder_path, filename)
            # 构建新的JPG文件名
            jpg_filename = os.path.splitext(filename)[0] + '.jpg'
            jpg_path = os.path.join(folder_path, jpg_filename)

            try:
                # 打开PNG图片
                with Image.open(png_path) as img:
                    # 转换图片到RGB模式（JPG不支持透明度）
                    rgb_img = img.convert('RGB')
                    # 保存为JPG
                    rgb_img.save(jpg_path, 'jpeg')
                    logging.info(f"成功转换 '{filename}' -> '{jpg_filename}'")
                    converted_count += 1

                # 如果设置为True，则删除原始PNG文件
                if DELETE_ORIGINAL_PNG:
                    os.remove(png_path)
                    logging.info(f"已删除原始文件: '{filename}'")

            except Exception as e:
                logging.error(f"转换 '{filename}' 时发生错误: {e}")
                skipped_count += 1
    
    logging.info("--- 转换完成 ---")
    logging.info(f"成功转换文件数: {converted_count}")
    logging.info(f"跳过/失败文件数: {skipped_count}")

if __name__ == "__main__":
    convert_png_to_jpg(TARGET_FOLDER)
